package com.rogan.rpc.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class JSONMessageProtocol implements MessageProtocol {

	@Override
	public byte[] marshallingRequest(Request req) {
		Request temp = new Request();
		temp.setServiceName(req.getServiceName());
		temp.setMethod(req.getMethod());
		temp.setHeaders(req.getHeaders());
		temp.setParameters(req.getParameters());
		temp.setParameterTypes(req.getParameterTypes());

		if (req.getParameters() != null) {
			Object[] params = req.getParameters();
			Object[] serizeParams = new Object[params.length];
			for (int i = 0; i < params.length; i++) {
				serizeParams[i] = JSON.toJSONString(params[i]);

			}
			temp.setParameters(serizeParams);
		}
		return JSON.toJSONBytes(temp);
	}

	@Override
	public Request unmarchallingRequest(byte[] data) {
		String rs = new String(data);
		Request request = JSON.parseObject(rs, Request.class);
		Object[] obj = request.getParameters();
		if (obj != null) {
			Object[] params  = new Object[obj.length];	
			for (int i = 0; i< obj.length; i++) {
				Class<?> type = request.getParameterTypes()[i];
				 Object s = JSON.parseObject(obj[i].toString(),type  );
				 params[i] = s;
			}
			request.setParameters(params);
		}
		return request;
	}

	@Override
	public byte[] marshallingRespose(Response rsp) {
		 Response temp = new Response();
		 temp.setException(rsp.getException());
		 temp.setHeaders(rsp.getHeaders());
		 temp.setReturnType(rsp.getReturnType());
		 temp.setReturnValue(rsp.getReturnValue());
		 temp.setStatus(rsp.getStatus());
		 return JSON.toJSONBytes(temp);
	}

	@Override
	public Response unmarshallingResponse(byte[] data) {
		String rs = new String(data);
		Response response = JSON.parseObject(rs, Response.class);
		return response;
	}

}
